package cn.uestc.labhms.modules.hms.controller;

import cn.uestc.labhms.common.annotation.SysLog;
import cn.uestc.labhms.common.utils.R;
import cn.uestc.labhms.modules.hms.exception.HMSException;
import cn.uestc.labhms.modules.hms.param.ConstParam;
import cn.uestc.labhms.modules.hms.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
public class ExcelController {
    @Autowired
    private ExcelService excelService;

    @PostMapping("/post/upload")
    @SysLog("导入数据")
    public R uploadAndImport(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new HMSException("上传文件为空或者上传文件内容为空");
        }
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
        // 判断是否是可以接收的文件
        if (!ConstParam.FILE_SUFFIX.contains(suffix)) {
            throw new HMSException("仅允许上传xls或xlsx文件");
        }
        excelService.uploadAndImport(file);
        return R.ok("导入成功");
    }

}
